package com.dragon.app.config.aop;


import com.alibaba.fastjson.JSONObject;
import com.dragon.app.config.annotation.AddPage;
import com.dragon.logical.service.auth.IExamineService;
import com.dragon.repository.entity.AddPageData;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

@Aspect
@Component
@Slf4j
public class  AddPageAop {

    @Autowired
    IExamineService service;


    @Pointcut("@annotation(com.dragon.app.config.annotation.AddPage)")
    public void addPagePointCut(){

    }


    @AfterReturning(pointcut = "addPagePointCut()",returning = "returnValue")
    public void doAfterReturning(JoinPoint joinPoint,Object returnValue)throws IOException{
        Map<String,Object> result = JSONObject.parseObject(JSONObject.toJSONString(returnValue),Map.class);
        handleOperationRecord(joinPoint,result.get("data"));
    }

    private void handleOperationRecord(JoinPoint joinPoint,Object returnValue)throws IOException{
        //操作记录记录到数据库中
        service.addExamine(JSONObject.parseObject(JSONObject.toJSONString(returnValue), AddPageData.class));
    }

    /**
     * 是否存在注解，如果存在就获取，不存在则返回null
     * @param joinPoint
     * @return
     */
    private AddPage getAnnotation(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(AddPage.class);
        }
        return null;
    }


}
